package com.sz.biz.logistics.core.service.impl;

import com.sz.biz.common.constants.CommCodes;
import com.sz.biz.common.constants.ErrorCodes;
import com.sz.biz.common.constants.ModuleNames;
import com.sz.biz.logistics.base.entity.*;
import com.sz.biz.logistics.base.service.*;
import com.sz.biz.logistics.constants.SubServiceTypes;
import com.sz.biz.logistics.core.dto.ServiceClassDto;
import com.sz.biz.logistics.core.entity.ServiceClassRel;
import com.sz.biz.logistics.core.entity.ServiceRegionRel;
import com.sz.biz.logistics.core.entity.ServiceTypeRel;
import com.sz.biz.logistics.core.service.ServiceClassRelService;
import com.sz.biz.logistics.core.service.ServiceRegionRelService;
import com.sz.biz.logistics.core.service.ServiceService;
import com.sz.biz.logistics.core.service.ServiceTypeRelService;
import com.sz.common.base.constants.UserActions;
import com.sz.common.base.exception.Exceptions;
import com.sz.common.base.service.AbstractService;
import com.sz.common.base.utils.CollectionUtils;
import com.sz.common.base.utils.EntityUtils;
import com.sz.common.core.service.PrincipalLogUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * Function: ServiceCargoTypeRelServiceImpl. <br>
 * Date: 2017年03月14日 14:27 <br>
 * Author: wentao.chang
 */
@Service
public class ServiceClassRelServiceImpl extends AbstractService implements ServiceClassRelService {


    @Autowired
    private ServiceService serviceService;

    @Autowired
    private ServiceTypeRelService serviceTypeService;

    @Autowired
    private ServiceRegionRelService serviceRegionRelService;

    @Autowired
    private AirlineDetailService airlineDetailService;

    @Autowired
    private ShippingLineDetailService shippingLineDetailService;

    @Autowired
    private AirportService airportService;

    @Autowired
    private PortService portService;

    @Autowired
    private RegionSchemaService regionSchemaService;


    @Override
    public void save(String uid, ServiceClassDto serviceClassDto) {
        com.sz.biz.logistics.core.entity.Service service = serviceService.findActivedByUid(uid);
        if (service == null) {
            throw Exceptions.bizException(ErrorCodes.ERROR_ARGUMENT_ILLEGAL, "uid");
        }
        List<ServiceTypeRel> sts = serviceTypeService.findByRefId(service.getId());
        if (CollectionUtils.isEmpty(sts)) {
            throw Exceptions.bizException(ErrorCodes.ERROR_ARGUMENT_ILLEGAL, "uid");
        }
        sts.get(0).setLineId(serviceClassDto.getLineId());
        serviceTypeService.deleteByServiceId(service.getId());
        serviceTypeService.save(sts);

        List<ServiceClassRel> list = new ArrayList<>();
        for (int classId : serviceClassDto.getClassIds()) {
            ServiceClassRel rel = new ServiceClassRel();
            rel.setServiceId(service.getId());
            rel.setClassId(classId);
            list.add(rel);
        }
        deleteByServiceId(service.getId());
        dao.batchInsert("ServiceClassRelMapper.insert", list);

        serviceRegionRelService.deleteByServiceId(service.getId());

        if (sts.get(0).getSubServiceTypeCode().equals(SubServiceTypes.MAINLINE_AIR)) {
            List<AirlineDetail> ald = airlineDetailService.findByAirlineId(serviceClassDto.getLineId());
            if(!org.apache.commons.collections.CollectionUtils.isEmpty(ald)){
                saveRegion(service.getId(), CommCodes.PRODUCT_SERVICE_REGION_START, 6, Collections.singletonList(ald.get(0).getAirportId()));
                ald.remove(0);
                saveRegion(service.getId(), CommCodes.PRODUCT_SERVICE_REGION_END, 6, EntityUtils.getIntPropListFromBeans(ald, "airportId"));
            }

        }
        if (sts.get(0).getSubServiceTypeCode().equals(SubServiceTypes.MAINLINE_SHIP)) {
            List<ShippingLineDetail> sld = shippingLineDetailService.findByShippingLineId(serviceClassDto.getLineId());
            if(!org.apache.commons.collections.CollectionUtils.isEmpty(sld)){

                saveRegion(service.getId(), CommCodes.PRODUCT_SERVICE_REGION_START, 5, Collections.singletonList(sld.get(0).getPortId()));
                sld.remove(0);
                saveRegion(service.getId(), CommCodes.PRODUCT_SERVICE_REGION_END, 5, EntityUtils.getIntPropListFromBeans(sld, "portId"));
            }
        }
        //保存操作日志
        Map<String, Object> dataBackup = new HashMap<>();
        dataBackup.put("ADD_SERVICE_CLASS", list);
        PrincipalLogUtils.addOperationLog(ModuleNames.BIZ, ModuleNames.BIZ_SERVICE_CLASS, UserActions.ADD, "新增服务班次", dataBackup);
    }

    /**
     * preCode 6 空运  5海运
     *
     * @param serviceId  serviceId
     * @param regionType s e
     * @param preCode    6 空运  5海运
     */
    private void saveRegion(Integer serviceId, String regionType, int preCode, List<Integer> portIds) {
        RegionSchema regionSchema = new RegionSchema();
        regionSchema.setDescription("干线服务冗余" + ("s".equals(regionType) ? "开始" : "终止") + "分区");
        regionSchema.setAddressType(preCode == 6 ? 6 : 1);
        regionSchema.setCode(UUID.randomUUID().toString());
        regionSchema.setName(UUID.randomUUID().toString());
        regionSchema.setType(4);
        StringBuilder sb = new StringBuilder();
        for (Integer portId : portIds) {
            RegionItem item = new RegionItem();
            //空运
            if (preCode == 6) {
                Airport port = airportService.findShortById(portId);
                item.setType(preCode);
                if (port != null) {
                    item.setCountry(port.getCountryId());
                    item.setAreaId(port.getCityId());
                    sb.append(item.getDetailString()).append("|");
                }
            }
            //海运
            if (preCode == 5) {
                Port port = portService.findShortById(portId);
                item.setType(preCode);
                if (port != null) {
                    item.setCountry(port.getCountryId());
                    item.setAreaId(port.getCityId());
                    sb.append(item.getDetailString()).append("|");
                }
            }
        }
        regionSchema.setItemDetail(sb.toString());
        String suuid = regionSchemaService.save(regionSchema);


        ServiceRegionRel entry = new ServiceRegionRel();
        entry.setServiceId(serviceId);
        entry.setType(regionType);
        entry.setSchemaUid(suuid);
        serviceRegionRelService.save(entry);
    }

    @Override
    public void save(List<ServiceClassRel> list) {
        dao.batchInsert("ServiceClassRelMapper.insert", list);
        //保存操作日志
        Map<String, Object> dataBackup = new HashMap<>();
        dataBackup.put("ADD_SERVICE_CLASS", list);
        PrincipalLogUtils.addOperationLog(ModuleNames.BIZ, ModuleNames.BIZ_SERVICE_CLASS, UserActions.ADD, "新增服务班次", dataBackup);
    }

    @Override
    public List<ServiceClassRel> findByRefId(int refId) {
        return dao.findForList("ServiceClassRelMapper.findByRefId", refId, ServiceClassRel.class);
    }


    @Override
    public void deleteByServiceId(Integer serviceId) {
        dao.delete("ServiceClassRelMapper.deleteByServiceId", serviceId);
        //保存操作日志
        Map<String, Object> dataBackup = new HashMap<>();
        dataBackup.put("DELETE_SERVICE_CLASS", serviceId);
        PrincipalLogUtils.addOperationLog(ModuleNames.BIZ, ModuleNames.BIZ_SERVICE_CLASS, UserActions.DELETE, "删除服务班次", dataBackup);
    }

    @Override
    protected String getMapperNamespace() {
        return "ServiceClassRelMapper";
    }
}
